package com.homework.loans;

import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.joda.time.DateTime;

import java.util.Optional;

import static java.util.Optional.ofNullable;
import static org.hibernate.criterion.Restrictions.between;
import static org.hibernate.criterion.Restrictions.eq;
import static org.joda.time.DateTime.now;

/**
 * Provides CRUD for Load domain object.
 *
 * @author Blind
 */
public class LoanDao extends AbstractDAO<Loan> {
    /**
     * Creates a new DAO with a given session provider.
     *
     * @param sessionFactory a session provider
     */
    public LoanDao(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    /**
     * Create loan in DB.
     *
     * @param loan to create.
     * @return loan id.
     */
    public Loan create(Loan loan) {
        return persist(loan);
    }

    public long countFromIp(String ip) {
        return (long) criteria().add(eq("ip", ip)).
                add(between("startDate", now().withTimeAtStartOfDay(), now().withTimeAtStartOfDay().plusDays(1))).
                setProjection(Projections.count("ip")).uniqueResult();
    }

    public Optional<Loan> find(int loanId) {
        return ofNullable(get(loanId));
    }
}
